$(function() {
	 
	$("#ajax").ajaxSend(function(e, xhr, settings) {
 			  if (settings.url.indexOf('task')<0) {
 				    $(this).show();
				  }
				}).ajaxStop(function(){
			 $(this).hide();
		 }).ajaxError(function(){
			 $(this).hide();
    });
    
	//nav
	$a = $(".nav>ul>li");
	$a.children("ul>li:first-child").css("border-top", "0");
	$a.children("ul>li:last-child").css("border-bottom", "0");
	$a.hover(function() {
			$(this).addClass("current_tabs").children("ul").show();
	}, function() {
		if(!$(this).hasClass('active'))
		    $(this).removeClass("current_tabs").children("ul").hide();
		else
			$(this).children('ul').hide();
	});
	
	//定位左边菜单
	$(".btn_y").each(function(inx,ele){
		var data=$(ele).children('a').attr('data');
		var route=mod+con+act;
		if(data==route)
		   $(this).addClass("left_btn_h");
	});
	
})
//fast fn
/*$(function() {
	$(".btn_add").toggle(function() {
		$(this).addClass('left_btn_h').children("left_arrow").addClass("left_arrow_off").end().siblings(".btn_fn_list").slideDown();
	}, function() {
		$(this).removeClass('left_btn_h').children("left_arrow").addClass("left_arrow_off").end().siblings(".btn_fn_list").stop(true, true).slideUp();
	})
})*/
$(function() {
	$(".btn_add").click(function(){
		$(this).toggleClass('left_btn_h').children(".left_arrow").toggleClass("left_arrow_off");
		var btn_fn_list=$(this).siblings('.btn_fn_list');
		if($(this).siblings('.btn_fn_list').is(':visible')){
			$(btn_fn_list).slideUp();
		}else{
			$(btn_fn_list).slideDown();
		}
	})
})
//修改密码 查看消息
$(function() {
	$("#member").hover(function() {
		$('#head_notice_new').hide();
		$(this).addClass("member_h").children(".exit").show();
	}, function() {
		$(this).removeClass("member_h").children(".exit").hide();
		$('#head_notice_new').show();
	})
	$("#edit_pass").click(function() {
		win_setpwd = $.window({
			title : "修改密码",
			ajax_url : "index.php?r=users/setpwd",
			width : 400,
			height : 320
		});
	})
})
jQuery.extend({
	// 转义JQ选择器中的字符 $("."+jqSelector(selector)) $("#"+jqSelector(selector))
	jqSelector : function(name) {
		return name
		.replace(/([;&,\.\+\*\~\':\"\!\^#$%@\[\]\(\)=>\|])/g, '\\$1');
	}
});

jQuery(function() {
	$('.ccs').each(function(index, element) {
		var e = element;
		var r = $(this).attr('data');
		var p=$(this).attr('param');
		var k=$(this).attr('key');
		var c=$(this).attr('cache');
		$.get(rootUrl + '?r=home/checkcanshow', {
			resource : r,param:p,useCache:c,key:k
		}, function(data) {

			if (data.status == 1) {
				$(e).after(data.data);
			}
			$(e).remove();
		}, 'json');
	});
});

$(document).ready(function() {
	flexiGridTimeout = setTimeout("$('table.items').flexigrid({height:'auto'})",3000);
	//console.log(typeof(a));
	//setTimeout("$('.items').flexigrid({height:'auto'})",3500);
	//setTimeout("$('.items').flexToggleCol(1)",3500);
	//setTimeout("$('.items').flexToggleCol(1)",3000);
	//setTimeout("console.log($('.items').grid)",4000);
	//setTimeout("$('.items').",3500);
	//setTimeout("console.log('aa'+$('.items').grid)",3500);
	//$('.items').flexToggleCol(1);
	//console.log($('.toggle').grid);
	//$(".items").flexigrid({"height":'auto'});
	//console.log($('.items').grid);
	$('.drag_table').flexigrid({height:'auto',showToggleBtn:false,isAddDiv:true});
});
//fold left
$(document).ready(function() {
	$('#btn_fold').toggle(function() {
		$(this).addClass('fold_off');
		$('.left').hide().siblings('.right').css({
			'margin-left' : '21px',
		});
		$('body').addClass('main_body_h');
	}, function() {
		$(this).removeClass('fold_off');
		$('.left').show().siblings('.right').css({
			'margin-left' : '207px',
		});
		$('body').removeClass('main_body_h');
	})
});
//搜索折叠
$(function(){
	$("#search_f_d").toggle(function(){
		$(this).addClass("search_f_t").siblings(".search_form_b").slideDown()
	},function(){
		$(this).removeClass("search_f_t").siblings(".search_form_b").slideUp()
	})
})

//$(function() {
//$(".tips").poshytip();
//});

//input focus
$.fn.input_focus= function(){
	$(this).each(function(){
		var defaultValue = $(this).attr('input_tips');
		$(this).bind("focus",function(){
			$(this).removeClass("color_lg");

			if($(this).attr("id")=="password")
				$(this).removeClass("pw").removeClass("pw_wc");

			if($(this).val()==defaultValue)
				$(this).val(""); 

		}).bind("blur",function(){
			if($(this).val()==""){
				$(this).val(defaultValue);
				$(this).addClass("color_lg");
				if($(this).attr("id")=="password")
					$(this).addClass("pw_wc");
			}
		}).bind("change",function(){
			if($(this).val()==""){
				$(this).addClass("color_lg");
				if($(this).attr("id")=="password")
					$(this).addClass("pw").addClass("pw_wc");
			}else{
				$(this).removeClass("color_lg");
				if($(this).attr("id")=="password")
					$(this).removeClass("pw").removeClass("pw_wc");
			}
		});
	})
}
$(function() {
	$("input[input_tips]").input_focus();
});
//alert js
(function($) {	
	$.alerts = {
			// These properties can be read/written by accessing $.alerts.propertyName from your scripts at any time
			verticalOffset: -75,                // vertical offset of the dialog from center screen, in pixels
			horizontalOffset: 0,                // horizontal offset of the dialog from center screen, in pixels/
			repositionOnResize: true,           // re-centers the dialog on window resize
			showBg:true,						//	tuck edit for background opacity
			overlayOpacity: 0,                // transparency level of overlay
			overlayColor: '#eee',               // base color of overlay
			draggable: true,                    // make the dialogs draggable (requires UI Draggables plugin)
			okButton: '确定',         // text for the OK button
			cancelButton: '取消', // text for the Cancel button
			dialogClass: null,                  // if specified, this class will be applied to all dialogs
			alertIcon:'warn', //tuck edit warn default  or success error

			// Public methods

			alert: function(message, title, callback) {
				if( title == null ) title = '提示';
				$.alerts._show(title, message, null, 'alert', function(result) {
					if( callback ) callback(result);
				});
			},

			confirm: function(message, title, callback) {
				if( title == null ) title = '提示';
				$.alerts._show(title, message, null, 'confirm', function(result) {
					if( callback ) callback(result);
				});
			},

			prompt: function(message, value, title, callback) {
				if( title == null ) title = '警告';
				$.alerts._show(title, message, value, 'prompt', function(result) {
					if( callback ) callback(result);
				});
			},

			// Private methods

			_show: function(title, msg, value, type, callback) {

				$.alerts._hide();
				//$.alerts._overlay('show');
				$.alerts._overlay($.alerts.showBg);

				$("BODY").append(
						'<div id="popup_container">' +
						'<h1 id="popup_title"></h1>' +
						'<div class="popup_c_warp"><div id="popup_content" class="clearfix">' +
						'<div id="popup_message"></div><div id="pop_up_bg"></div>' +
						'</div></div>' +
				'</div>');

				if( $.alerts.dialogClass ) $("#popup_container").addClass($.alerts.dialogClass);

				// IE6 Fix
				var pos = ($.browser.msie && parseInt($.browser.version) <= 6 ) ? 'absolute' : 'fixed'; 

				$("#popup_container").css({
					position: pos,
					zIndex: 99999
				});

				$("#popup_title").text(title);
				//edit by tuck  $("#popup_content").addClass(type);
				if(type=='alert')
					$("#popup_content").addClass($.alerts.alertIcon);
				else
					$("#popup_content").addClass(type);
				$("#popup_message").text(msg);
				$("#popup_message").html( $("#popup_message").text().replace(/\n/g, '<br />') );

				$("#popup_container").css({
					minWidth: $("#popup_container").outerWidth(),
					maxWidth: $("#popup_container").outerWidth()
				});

				$.alerts._reposition();
				$.alerts._maintainPosition(true);

				switch( type ) {
				case 'alert':
					$("#popup_message").after('<div id="popup_panel" class="clearfix"><div class="btn_common btn_green"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /></div></div>');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						callback(true);
					});
					//$("#popup_ok").focus().keypress( function(e) { eidt by tuck
					$("#popup_ok").keypress( function(e) {
						if( e.keyCode == 13 || e.keyCode == 27 ) $("#popup_ok").trigger('click');
					});
					break;
				case 'confirm':
					$("#popup_message").after('<div id="popup_panel" class="clearfix"><div class="btn_common btn_green"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /></div><div class="btn_common btn_grey"><input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" /></div></div>');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						if( callback ) callback(true);
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback(false);
					});
					//$("#popup_ok").focus(); eidt by tuck
					$("#popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
					break;
				case 'prompt':
					$("#popup_message").append('<br /><input type="text" size="30" id="popup_prompt" />').after('<div id="popup_panel"><input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" /></div>');
					$("#popup_prompt").width( $("#popup_message").width() );
					$("#popup_ok").click( function() {
						var val = $("#popup_prompt").val();
						$.alerts._hide();
						if( callback ) callback( val );
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback( null );
					});
					$("#popup_prompt, #popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
					if( value ) $("#popup_prompt").val(value);
					$("#popup_prompt").focus().select();
					break;
				}

				// Make draggable
				if( $.alerts.draggable ) {
					try {
						$("#popup_container").draggable({ handle: $("#popup_title") });
						$("#popup_title").css({ cursor: 'move' });
					} catch(e) { /* requires jQuery UI draggables */ }
				}
			},

			_hide: function() {
				$("#popup_container").remove();
				//$.alerts._overlay('hide');
				$.alerts._overlay(false);
				$.alerts._maintainPosition(false);
			},

			_overlay: function(status) {
				switch( status ) {
				//case 'show':
				case true:
					//$.alerts._overlay('hide');
					$.alerts._overlay(false);
					$("BODY").append('<div id="popup_overlay"></div>');
					$("#popup_overlay").css({
						//position: 'absolute', tuck eidt
						//zIndex: 99998,
						//top: '0px',
						//left: '0px',
						//width: '100%',
						//height: $(document).height(),
						background: $.alerts.overlayColor,
						opacity: $.alerts.overlayOpacity
					});
					break;
					//case 'hide':
				case false:
					$("#popup_overlay").remove();
					break;
				}
			},

			_reposition: function() {
				var top = (($(window).height() / 2) - ($("#popup_container").outerHeight() / 2)) + $.alerts.verticalOffset;
				var left = (($(window).width() / 2) - ($("#popup_container").outerWidth() / 2)) + $.alerts.horizontalOffset;
				if( top < 0 ) top = 0;
				if( left < 0 ) left = 0;

				// IE6 fix
				if( $.browser.msie && parseInt($.browser.version) <= 6 ) top = top + $(window).scrollTop();

				$("#popup_container").css({
					top: top + 'px',
					left: left + 'px'
				});
				//$("#popup_overlay").height( $(document).height() ); tuck eidt
			},

			_maintainPosition: function(status) {
				if( $.alerts.repositionOnResize ) {
					switch(status) {
					case true:
						$(window).bind('resize', $.alerts._reposition);
						break;
					case false:
						$(window).unbind('resize', $.alerts._reposition);
						break;
					}
				}
			}

	}

	// Shortuct functions
	jAlert = function(message, title, callback) {
		$.alerts.alert(message, title, callback);
	}

	jConfirm = function(message, title, callback) {
		$.alerts.confirm(message, title, callback);
	};

	jPrompt = function(message, value, title, callback) {
		$.alerts.prompt(message, value, title, callback);
	};

})(jQuery);

//footer submit advice
$(function() {
	$("#sendAdvice").click(function() {
		win_advice = $.window({
			title : "我要提问",
			ajax_url : "index.php?r=advice/create",
			width : 500,
			height : 470
		});
	});
});

//include commonCssJs
function getLoader(){
	var url ='/js/loader.js';
	getJs(url, 'Jloader');
}

/**
 * include js
 * 
 * string url js地址
 * string sId js脚本标识id
 * int async 1异步引入，默认0同步引入
 */
function getJs(url, sId, async){
	var Skip = {};
    //获取XMLHttpRequest对象(提供客户端同http服务器通讯的协议)
    Skip.getXmlHttpRequest = function () {
        if (window.XMLHttpRequest) // 除了IE外的其它浏览器
            return new XMLHttpRequest();
        else if (window.ActiveXObject) // IE
            return new ActiveXObject("MsXml2.XmlHttp");
    };
    //导入内容
    Skip.includeJsText = function (jsText) {
    	var rootObject = document.getElementsByTagName("head")[0];
        if (rootObject != null) {
            var oScript = document.createElement("script");
            oScript.type = "text/javascript";
            oScript.id = sId;
            oScript.text = jsText;
            rootObject.appendChild(oScript);
        }
    };
    Skip.addJs = function () {
    	var i = 0;
    	var oScript = document.getElementById(sId);
    	if(oScript != null) return false;
    	
    	async = (typeof async!="undefined" && async==1) ? true : false;
        var oXmlHttp = Skip.getXmlHttpRequest();
        oXmlHttp.onreadystatechange = function () {
            if (oXmlHttp.readyState == 4) {
                if (oXmlHttp.status == 200 || oXmlHttp.status == 304) {
                	Skip.includeJsText(oXmlHttp.responseText);
                } else {
                	if(i < 4){
	                	oXmlHttp.open('GET', url, async);
	                    oXmlHttp.send(null);
                	}else{
                		alert('XML request error: ' + oXmlHttp.statusText + ' (' + oXmlHttp.status + ')');
                	}
                }
            }
        }
        oXmlHttp.open('GET', url, async);
        oXmlHttp.send(null);
    };
    Skip.addJs();
}

$(function(){
	// 幫有 placeholder 屬性的輸入框加上提示效果
	$('input[placeholder]').placeholder();
});
/*
 * Placeholder plugin for jQuery
 * ---
 * Copyright 2010, Daniel Stocks (http://webcloud.se)
 * Released under the MIT, BSD, and GPL Licenses.
 */
(function($) {
	function Placeholder(input) {
		this.input = input;
		if (input.attr('type') == 'password') {
			this.handlePassword();
		}
		// Prevent placeholder values from submitting
		$(input[0].form).submit(function() {
			if (input.hasClass('placeholder') && input[0].value == input.attr('placeholder')) {
				input[0].value = '';
			}
		});	
	}
	Placeholder.prototype = {
			show : function(loading) {
				// FF and IE saves values when you refresh the page. If the user refreshes the page with
				// the placeholders showing they will be the default values and the input fields won't be empty.
				if (this.input[0].value === '' || (loading && this.valueIsPlaceholder())) {
					if (this.isPassword) {
						try {
							this.input[0].setAttribute('type', 'text');
						} catch (e) {
							this.input.before(this.fakePassword.show()).hide();
						}
					}
					this.input.addClass('placeholder');
					this.input[0].value = this.input.attr('placeholder');
				}
			},
			hide : function() {
				if (this.valueIsPlaceholder() && this.input.hasClass('placeholder')) {
					this.input.removeClass('placeholder');
					this.input[0].value = '';
					if (this.isPassword) {
						try {
							this.input[0].setAttribute('type', 'password');
						} catch (e) { }
						// Restore focus for Opera and IE
						this.input.show();
						this.input[0].focus();
					}
				}
			},
			valueIsPlaceholder : function() {
				return this.input[0].value == this.input.attr('placeholder');
			},
			handlePassword: function() {
				var input = this.input;
				input.attr('realType', 'password');
				this.isPassword = true;
				// IE < 9 doesn't allow changing the type of password inputs
				if ($.browser.msie && input[0].outerHTML) {
					var fakeHTML = $(input[0].outerHTML.replace(/type=(['"])?password\1/gi, 'type=$1text$1'));
					this.fakePassword = fakeHTML.val(input.attr('placeholder')).addClass('placeholder').focus(function() {
						input.trigger('focus');
						$(this).hide();
					});
					$(input[0].form).submit(function() {
						fakeHTML.remove();
						input.show()
					});
				}
			}
	};
	var NATIVE_SUPPORT = !!("placeholder" in document.createElement( "input" ));
	$.fn.placeholder = function() {
		return NATIVE_SUPPORT ? this : this.each(function() {
			var input = $(this);
			var placeholder = new Placeholder(input);
			placeholder.show(true);
			input.focus(function() {
				placeholder.hide();
			});
			input.blur(function() {
				placeholder.show(false);
			});

			// On page refresh, IE doesn't re-populate user input
			// until the window.onload event is fired.
			if ($.browser.msie) {
				$(window).load(function() {
					if(input.val()) {
						input.removeClass("placeholder");
					}
					placeholder.show(true);
				});
				// What's even worse, the text cursor disappears
				// when tabbing between text inputs, here's a fix
				input.focus(function() {
					if(this.value == "") {
						var range = this.createTextRange();
						range.collapse(true);
						range.moveStart('character', 0);
						range.select();
					}
				});
			}
		});
	}
})(jQuery);

//改变步骤
function changeStepLabel(index) 
{
	$('.step span').removeClass();
	$('.step span').eq(index).addClass('step_curr');
}

/**
 * 用户信息
 * @param id 元素ID
 * @param multiple 是否多选
 * @param width 宽度
 * @param url 路径
 */
function user(id,multiple,width,url)
{

	if(url=='')
	{
		url=rootUrl+"?r=users/alluser";
	}
	$("#"+id).select2({
		width:width+'px',
		multiple: multiple,
		placeholder: "请选择...",
		allowClear:true,
		//openOnEnter:true, //按enter键生成任意字符
		ajax:{
			url:url,
			dataType: 'json',//可以是ajax jsonp 或者ajax自有参数
			quietMillis: 100,//延迟时间
			data: function (term, page) {
				return {
					q: term, // search term
					page_limit: 15,
					page:page
				};
			},
			results: function (data, page) {

				var more = (page * 15) < data.total;
				return {results: data.data,more:more};
			},

		}, 

		minimumInputLength:2,//搜索输入最少字符数
		//minimumResultsForSearch:2,
		maximumSelectionSize:5,//最d多只能出现几个标签
		formatResult: userFormatResult, // omitted for brevity, see the source of this page
		formatSelection: userFormatSelection, // omitted for brevity, see the source of this page
		initSelection: multiple?userMultiInitSelection:userInitSelection, // omitted for brevity, see the source of this page

	}) ;
}

function userMultiInitSelection(element,callback){
	var data=[] ;
	$(element.val().split("-")).each(function (ind,val) {
		var t=val.split(",");
		var dept=t[2]?t[2]:'';
		data.push({id:t[0], name:t[1],deptname:dept});
	});
	
	callback(data);

}

function userMultiFormatSelection(data, container) {
	return data;
}
function userInitSelection(element,callback)
{
	var t=element.val().split(","); 
	var data={id: t[0], name: t[1],deptname:t[2],companyname:t[3]};
	//重新赋值
	$(element).val(data.id);
	callback(data);
}
function userFormatResult(data, container, query) {
	return "<p >"+data.name+"  "+data.deptname+"  "+data.companyname+"<p>";
}
function userFormatSelection(data, container) {
    
	return data.name+"  "+data.deptname;

}

//有名为“disabled” 的class的元素不可点击
$(function(){
	$(".disabled").live('click',function(){
		return false;
	})
})

//搜索订单

function searchOrder(id)
{   
	id="#"+id;
	var val=$.trim($(id).val());
	 
	if(val=='')
		return false;
	var url=rootUrl+"?r=list/history&"+$(id).attr('name')+"="+val;
	window.location.href=url;
	return false;
}
//显示错误提示
function showMessage($err)
{
	$.each($err,function(i,ele){
		$("#"+i).addClass('border_r').attr('title',ele).trigger('focus');

	});
}
function afterUpdate(){}

/*
*自动消失提示
* $.messagetip({message:'message',callbackfun :function(){}});
* isOk : (true/false) false则显示错误图标
* message : 要显示的提示信息，默认为“成功”
* fadeintime: 多少秒后自动消失，默认为1.5秒
* messageclass: 用于自定义class 
* callbackfun: 执行完后的回调函数
* */
jQuery.extend({
    messagetip : function(setting){
        var defaults = {
			isOk:true,
            message : '成功',
            fadeintime : 1500,
            mTipsClass : '',
            callbackfun : null
        }
        var config = $.extend( defaults, setting || {});
        $("."+config.messageclass).remove();

        var window_width     = $(window).width();
        var window_height    = $(window).height();
        var scroll_top       = document.documentElement.scrollTop;
		var message_icon	 =config.isOk ? 'mTips_ok':'mTips_no';
        var rand = 'removeid_' + parseInt(Math.random()*1000000);
        $("body").append('<div class="mTips disn '+config.mTipsClass+'" id="'+rand+'"><p class="mTips_c"><span class="'+message_icon+'">'+config.message+'</span></p><div class="mTips_warp"></div></div>');
        var div_width         = $("."+config.messageclass).width();
        var div_height        = $("."+config.messageclass).height();
        move_left = ((window_width - div_width)/2);
        move_top = ((window_height- div_height)/2)+scroll_top;
        $("#"+rand).css({"left":move_left,"top":move_top,'position':'absolute'}).fadeIn();
        setTimeout(function()
                   {
                       $("#"+rand).fadeOut("slow",function(){
                            $("."+rand).remove();
							if (typeof config.callbackfun == 'function') {
								config.callbackfun.call(this); // 执行回调函数
						   }
                       });
              
                   },
        config.fadeintime);
    }
});
/*
s:为金额，数字或浮点型
n:为小数位数
*/
function numberFormat(s, n)  {
   if(s==undefined || s=='') return '';
   n = n > 0 && n <= 20 ? n : 2;
   s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
   var l = s.split(".")[0].split("").reverse(),
   r = s.split(".")[1];
   t = "";
   var i=0;
   for(i; i < l.length; i ++ )
   {
      t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
   }
   return t.split("").reverse().join("") + "." + r;
}